package view;

import dao.adminDao;
import model.Admin;
import util.dbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @program: foodApp
 * @description: This is a admin control servlet
 * @author: PanKer
 * @create: 2021-11-19 17:06
 */

@WebServlet("/adminVerification")
public class adminVerification extends HttpServlet {
    private static final long serialVersionUID = 6576728940361681005L;


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        boolean loginCheck = false;
        Admin admin = null;
        Connection conn = null;
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            conn = dbUtil.getConn();
            System.out.println("admin 数据库连接成功，身份验证成功");
            admin = new Admin(username, password);

            if (adminDao.isExist(conn, username)) {
                System.out.println("账号存在");
                admin = adminDao.login(conn, admin);
                if (admin != null) {
                    System.out.println("成功打印输出");
                    loginCheck = true;
                } else {
                    System.out.println("提示密码错误");
                }
            } else {
                System.out.println("提示该用户不存在");
            }
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException错误");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("SQLException错误");
            e.printStackTrace();
        } finally {
            try {
                System.out.println("数据库已关闭");
                conn.close();
            } catch (SQLException e) {
                System.out.println("数据库关闭失败");
                e.printStackTrace();
            }
        }

        StringBuilder json = new StringBuilder();
        if (loginCheck) {
            HttpSession session = req.getSession();
            session.setAttribute("admin", admin);
            json.append("{\"success\" : true}");
        } else {
            json.append("{\"success\" : false}");
        }

        resp.setContentType("application/json; charset=utf-8");
        resp.getWriter().print(json);
    }
}
